﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using System.Drawing;
using WPF.Themes;
//using WPFToolkit;
using TvdbConnector;
using TvdbConnector.Cache;
using TvdbConnector.Data;
using TvdbConnector.Data.Banner;
using TvdbConnector.Exceptions;
using System.Threading;

namespace DCShow_Browser
{
    /// <summary>
    /// Logique d'interaction pour Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        private object dummyNode = null;
        private Tvdb _tvdbHandler;
        private TvdbUser _tvdbUser;
        //private TvdbUser.

        #region private fields
        private List<TvdbBanner> m_imageList;
        private int m_index = 0;
        private System.Drawing.Image m_defaultImage;
        //private Size m_buttonSize;
        private Thread m_latestLoadingThread; //thread that loads the LATEST image (which should be shown after loading)
        //private Color m_loadingBackgroundColor = Color.;
        private System.Drawing.Image m_unavailableImage;
        #endregion

        public Window1()
        {
            this.InitializeComponent();
            _tvdbHandler = new Tvdb(new XmlCacheProvider(@"D:\\Temp\"), "69C6FDC7E5F4B985");
            _tvdbUser = new TvdbUser("Danone-KiD", "401D8B31F9832AA3");
            
            _tvdbHandler.UserInfo = _tvdbUser;
            _tvdbUser.UserPreferredLanguage = _tvdbHandler.GetPreferredLanguage();
            //_tvdbHandler.
            _tvdbHandler.InitCache();


            //Charge le dossier des séries
            foreach (string s in Directory.GetDirectories(@"D:\Perso\Series\"))
            {
                TreeViewItem item = new TreeViewItem();
                item.Header = s.Substring(s.LastIndexOf("\\") + 1);
                item.Tag = s;
                item.FontWeight = FontWeights.Normal;
                item.Items.Add(dummyNode);
                item.Expanded += new RoutedEventHandler(GetSubDirectories);
                item.Selected += new RoutedEventHandler(SelectSerie);

                ListeDossiers.Items.Add(item);
            }



        }
        void SelectSerie(object sender, RoutedEventArgs e)
        {
            TreeViewItem item = (TreeViewItem)sender;
            String sURIBanner;
            sURIBanner = @item.Tag.ToString() + "\\Banner.jpg";
            //this.Cursor = Cursors.Hand;

            if (File.Exists(sURIBanner))
            {
                Uri src = new Uri(sURIBanner);

                BitmapImage bi3 = new BitmapImage();
                bi3.BeginInit();
                MemoryStream ms = new MemoryStream();
                // Save to a memory stream...
                System.Drawing.Image img = System.Drawing.Image.FromFile(sURIBanner);
                img.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                // Rewind the stream...
                ms.Seek(0, SeekOrigin.Begin);
                // Tell the WPF image to use this stream...
                
                bi3.StreamSource = ms;
                bi3.EndInit();
                // And your WPF image is ready to go! (good idea to close that stream once your image is loaded...)
                IMG_Banner.Source = bi3;
                //tvdbHandler.SaveCache();

                //Image img = new Image();
                //img.Source = new BitmapImage(src);


                //BitmapImage img = new BitmapImage();
                //img.CacheOption = BitmapCacheOption.OnLoad;
                //img.UriSource = src;
                //Banner.Source = new BitmapImage();
            }

        }


        void GetSubDirectories(object sender, RoutedEventArgs e)
        {
            TreeViewItem item = (TreeViewItem)sender;
            if (item.Items.Count == 1 && item.Items[0] == dummyNode)
            {
                item.Items.Clear();
                try
                {
                    foreach (string s in Directory.GetDirectories(item.Tag.ToString()))
                    {
                        TreeViewItem subitem = new TreeViewItem();
                        subitem.Header = s.Substring(s.LastIndexOf("\\") + 1);
                        subitem.Tag = s;
                        subitem.FontWeight = FontWeights.Normal;
                        subitem.Items.Add(dummyNode);
                        subitem.Expanded += new RoutedEventHandler(GetSubDirectories);
                        item.Items.Add(subitem);
                    }
                }
                catch (Exception) { }
            }

        }

        private void ListeDossiers_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {

        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {


            TvdbSeries s = _tvdbHandler.GetFullSeries(73255, _tvdbUser.UserPreferredLanguage, true);

            foreach(TvdbSeriesBanner b in s.SeriesBanners)
            {
                if (b.IsLoaded == false)
                {
                    b.LoadBanner();
                }
            }
            SAI_Overview.Text = s.Overview;

            
           
            //Banner.Source = s.SeriesBanners[0];

            //SetBannerImage(s.SeriesBanners[1]);
            BitmapImage bi3 = new BitmapImage();
            bi3.BeginInit();
            MemoryStream ms = new MemoryStream();
            // Save to a memory stream...
            s.SeriesBanners[0].Banner.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
            // Rewind the stream...
            ms.Seek(0, SeekOrigin.Begin);
            // Tell the WPF image to use this stream...
            bi3.StreamSource = ms;
            bi3.EndInit();
            // And your WPF image is ready to go! (good idea to close that stream once your image is loaded...)
            IMG_Banner.Source = bi3;
            _tvdbHandler.SaveCache();

            //     foreach (TvdbSeriesBanner BannerSerie in s.SeriesBanners)
            //{
            //    BannerSerie.LoadBanner();

            //       }



            //Banner _Banner = new Banner(@"D:\Perso\Series\Dr. House\test.jpg");

            //Banner.Source = _Banner.Image;




            //Banner.Source = new BitmapImage(new Uri(@"D:\Perso\Series\Dr. House\banner.jpg"));
        }

        private void SetBannerImage(TvdbBanner _value)
        {
            Thread imageLoader = new Thread(new ParameterizedThreadStart(DoBannerLoad));
            m_latestLoadingThread = imageLoader;
            imageLoader.Priority = ThreadPriority.Lowest;
            imageLoader.Name = "Imageloader_" + _value.BannerPath;
            imageLoader.Start(_value);

        }

        private void DoBannerLoad(object _param)
        {
            TvdbBanner banner = (TvdbBanner)_param;
            try
            {
                if (banner.BannerPath != null && !banner.BannerPath.Equals(""))
                {
                    int index = m_index;
                    if (!banner.IsLoaded)
                    {
                        SetImageThreadSafe(null);
                        SetLoadingVisibleThreadSafe(true);
                        banner.LoadBanner();
                    }

                    lock (m_latestLoadingThread)
                    {
                        if (Thread.CurrentThread == m_latestLoadingThread)
                        {
                            //Console.WriteLine("Loading finished of " + banner.Id);
                            if (banner.IsLoaded)
                            {//banner was successfully loaded
                                SetLoadingVisibleThreadSafe(false);
                                SetImageThreadSafe(banner.Banner);

                            }
                            else
                            {//couldn't load the banner
                                SetLoadingVisibleThreadSafe(false);
                            }
                        }
                        else
                        {
                            //Console.WriteLine("Didn't load " + banner.Id + " because it's not the latest image");
                        }
                    }
                }
                else
                {//no banner information available -> use default image if there is one
                    SetLoadingVisibleThreadSafe(false);
                    SetImageThreadSafe(m_unavailableImage);
                }
            }
            catch (ThreadAbortException)
            {
                //Console.WriteLine("Bannercontrol aborted loading");
            }
        }


        //#region threadsafe operations
        delegate void SetImageThreadSafeDelegate(System.Drawing.Image _image);
        void SetImageThreadSafe(System.Drawing.Image _image)
        {
            //if (!InvokeRequired)
            //{
            try
            {
                BitmapImage bi3 = new BitmapImage();
                bi3.BeginInit();
                MemoryStream ms = new MemoryStream();
                // Save to a memory stream...
                _image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                // Rewind the stream...
                ms.Seek(0, SeekOrigin.Begin);
                // Tell the WPF image to use this stream...
                bi3.StreamSource = ms;
                bi3.EndInit();
                // And your WPF image is ready to go! (good idea to close that stream once your image is loaded...)
                IMG_Banner.Source = bi3;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            //}
            //else
            //    Invoke(new SetImageThreadSafeDelegate(SetImageThreadSafe), new object[] { _image });
        }

        delegate void SetLoadingVisibleThreadSafeDelegate(bool _visible);
        void SetLoadingVisibleThreadSafe(bool _visible)
        {
            //if (!InvokeRequired)
            //{
            // try
            // {
            //pbLoading.Visible = _visible;
            // if (_visible)
            // {
            //   this.BackColor = m_loadingBackgroundColor;
            //    panelImage.BackColor = m_loadingBackgroundColor;
            //}
            //}
            //catch (Exception ex)
            //{
            //   Console.WriteLine(ex.ToString());
            //}
            //}
            //else
            //Invoke(new SetLoadingVisibleThreadSafeDelegate(SetLoadingVisibleThreadSafe), new object[] { _visible });
        }
    }
}
